import { observable, action } from 'mobx';
import { message } from 'antd';
import { WeaForm } from 'comsMobx';
import { WeaLocaleProvider } from 'ecCom';
import { ValidateForm } from './util';
import * as Api from '../../apis/setting/mailAutoRes';

const getLabel = WeaLocaleProvider.getLabel;
const initalState = {
  autoFields: [],
  autoRichValue: '',
};
export default class AutoRespondStore {
  @observable autoForm = new WeaForm();
  @observable autoFields = initalState.autoFields;
  @observable autoRichValue = initalState.autoRichValue;

  @action setStoreState = (params) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  };

  @action clear = () => this.setStoreState(initalState);

  @action getEmailAutoRespondCondition = () => {
    Api.getEmailAutoRespondCondition().then((res) => {
      this.autoForm.initFormFields(res.conditioninfo);
      this.autoFields = res.conditioninfo;
      this.getEmailAutoRespondEntity();
    });
  };

  @action getEmailAutoRespondEntity = (params) => {
    Api.getEmailAutoRespondEntity(params).then((res) => {
      let formParams = this.autoForm.getFormParams();
      this.autoRichValue = res.emailAutoRespondEntity.content || '';
      for (let attr in formParams) {
        if (
          Object.prototype.hasOwnProperty.call(res.emailAutoRespondEntity, attr)
        ) {
          this.autoForm.updateFields({
            [attr]: { value: res.emailAutoRespondEntity[attr] },
          });
        }
      }
    });
  };

  @action autoSubmit = (params) => {
    ValidateForm(this.autoForm, () => {
      let formParams = this.autoForm.getFormParams();
      params = { ...formParams, operation: 'update', ...params };
      Api.operateEmailAutoRespond(params).then((res) => {
        if (res.flag) {
          message.success(getLabel(384443, '更新设置成功'));
        } else {
          message.error(getLabel(384444, '更新设置失败'));
        }
      });
    });
  };
}
